<?php
class aluCriteria extends Criteria
{

  /**
   *
   * @param sfRequest $request
   * @return aluCriteria
   */
  public static function buildFromRequest(sfRequest $request)
  {
    $c = new aluCriteria();
    $filtres = ($request->hasParameter('filtres')) ? $request->getParameter('filtres') : array();
    if (array_key_exists('periode', $filtres))
    {
      $c->addFiltrePeriode($filtres['periode']);
    }
    if (array_key_exists('user', $filtres) && $filtres['user'] != 'Non')
    {
      $c->addFilterUser($filtres['user']);
    }
    if (array_key_exists('machine', $filtres) && $filtres['machine'] != 'Non')
    {
      $c->addFilterMachine($filtres['machine']);
    }
    if (array_key_exists('type', $filtres) && $filtres['type'] != 'Non')
    {
      $c->addFilterType($filtres['type']);
    }
    return $c;
  }

  public function addFiltrePeriode($periode)
  {
    if (is_array($periode) && array_key_exists('from', $periode) && array_key_exists('to', $periode))
    {
      if (array_key_exists('day', $periode['from'])
      && array_key_exists('month', $periode['from'])
      && array_key_exists('year', $periode['from'])
      && array_key_exists('day', $periode['to'])
      && array_key_exists('month', $periode['to'])
      && array_key_exists('year', $periode['to']) )
      {
        $pattern = '%s-%s-%s';
        $date1   = $this->dateToSql($periode['from']);
        $date2   = $this->dateToSql($periode['to']);
        $criterion = $this->getNewCriterion(LogPeer::DATE, $date1, Criteria::GREATER_EQUAL);
        $criterion->addAnd($this->getNewCriterion(LogPeer::DATE, $date2, Criteria::LESS_EQUAL));
        $this->add($criterion);
      }
    }
  }

  private function dateToSql($tab)
  {
    $pattern = '%s-%s-%s';
    $annee   = $tab['year'];
    $mois    = str_pad($tab['month'], 2, 0, STR_PAD_LEFT);
    $jour    = str_pad($tab['day'], 2, 0, STR_PAD_LEFT);
    $date    = sprintf($pattern, $annee, $mois, $jour);
    return $date;
  }

  public function addFilterUser($user)
  {
    $this->add(LogPeer::UTILISATEUR, $user);
  }

  public function addFilterMachine($machine)
  {
    $this->add(LogPeer::MACHINE, $machine);
  }

  public function addFilterType($type)
  {
    $this->add(LogPeer::TYPE, $type);
  }

}